﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sendz.WebUI.Models;
using System.ComponentModel;

namespace Sendz.WebUI.Binders
{
    public abstract class CustomModelBinder : IModelBinder
    {
        // Abstract methods
        public abstract object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext);

        // Methods
        protected virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //if (bindingContext.ModelType == typeof(IEnumerable<FormFieldViewModel>))
            //{
            object model = this.CreateModel(controllerContext, bindingContext);
            //foreach (var formField in (List<FormFieldViewModel>)model)
            //{
            foreach (ModelMetadata property in bindingContext.PropertyMetadata.Values)
            {
                // Get property value
                property.Model = bindingContext.ModelType.GetProperty(property.PropertyName).GetValue(model, null);

                // Get property validator
                foreach (ModelValidator validator in property.GetValidators(controllerContext))
                {
                    // Validate property
                    foreach (ModelValidationResult result in validator.Validate(model))
                    {
                        // Add error message into model state
                        bindingContext.ModelState.AddModelError(property.PropertyName + "." + result.MemberName, result.Message);
                    }
                }
            }
            //}
            return model;
            //}
            //return this.CreateModel(controllerContext, bindingContext);
        }

        // IModelBinder members
        object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return CreateModel(controllerContext, bindingContext);
            // return this.BindModel(controllerContext, bindingContext);
        }
    }
}